/**
	*@class importExport
	*@description A paraméterként kapott stringet beirja egy fájlba melyet mi választhatunk ki egy Filepicker segitségével.
	*
	*@author Propszt Istvan
	*
	*@param (string)
*/

function savetoFile(data){
	
	// FilePicker létrehozása
	
	const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); 
    fp.init(window, "Select a File", nsIFilePicker.modeSave);
    // Szürö hozzáaddása
	fp.appendFilter("iCalendar (*.ics)","*.ics");

    var rv = fp.show();
    
	// Ha sikeresen megnyitota a filet irásra.
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
        var file = fp.file;
        var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"].
               createInstance(Components.interfaces.nsIFileOutputStream);

        // use 0x02 | 0x10 to open file for appending.
        foStream.init(file, 0x02 | 0x08 | 0x20, 0666, 0); 
        var converter = Components.classes["@mozilla.org/intl/converter-output-stream;1"].
                createInstance(Components.interfaces.nsIConverterOutputStream);
        converter.init(foStream, "UTF-8", 0, 0);
		converter.writeString(data);			/*write data to file*/
        converter.close(); // this closes foStream
        return 0;
	}
	return -1;
}

/**
	*@class importExport
	*@description Export from datebase to *ics file
	*
	*@author Propszt Istvan
	*
	*@see getAllEvent
	*@see savetoFile
*/

function exportF() {
  
        var data = vcalendar + vtimezone;
        
		var repeat = "";
		var reminder = "";
		var adatok = getAllEvent();			/* Get all event from datebase */
		for ( var i = 0 ; i < adatok.length ; i++ ){
        
			reminder = "";
			repeat = adatok[i].repeatName;
			repeat = repeat.toUpperCase();
			if (repeat == "NO REPEAT"){
				repeat ="";
			}
			
			var rem = new Number(adatok[i].remind);
						
			var maradek = rem%60;
			rem = (rem - maradek)/60
			
			var maradek2 = rem%24;
			rem = (rem - maradek2)/24
			
			if (maradek2 != 0 || maradek !=0){
				reminder = maradek+"M0S\n";
				if (maradek<10){
					reminder = "0"+reminder;
				}
				reminder = rem+"DT"+maradek2+"H"+reminder
			}
			else{
				reminder = rem+"D\n";
			}			
			
			data = data + "BEGIN:VEVENT\nCREATED:2010"+""+doublenumber(adatok[i].month)+""+doublenumber(adatok[i].day)+"T"+doublenumber(adatok[i].hour)+doublenumber(adatok[i].minute)+"00Z\n"+
			                            "LAST-MODIFIED:2010"+""+doublenumber(adatok[i].month)+""+doublenumber(adatok[i].day)+"T"+doublenumber(adatok[i].hour)+doublenumber(adatok[i].minute)+"00Z\n"+
										"DTSTART:"+adatok[i].year+""+doublenumber(adatok[i].month)+""+doublenumber(adatok[i].day)+"T"+doublenumber(adatok[i].hour)+doublenumber(adatok[i].minute)+"00Z\n"+
										"DTEND:"+adatok[i].endYear+""+doublenumber(adatok[i].endMonth)+""+doublenumber(adatok[i].endDay)+"T"+doublenumber(adatok[i].endHour)+doublenumber(adatok[i].endMinute)+"00Z\n";
			if (repeat != ""){
				data = data + "RRULE:FREQ="+repeat+"\n";
			}
			var dd = new Date();
			data = data +				"DTSTAMP:2010"+doublenumber(adatok[i].month)+""+doublenumber(adatok[i].day)+"T"+doublenumber(adatok[i].hour)+doublenumber(adatok[i].minute)+""+dd.getSeconds()+"\n"+
										"UID:nfk"+i+doublenumber(adatok[i].month)+""+doublenumber(adatok[i].day)+"-2312n-"+doublenumber(adatok[i].endHour)+doublenumber(adatok[i].endMinute)+"@google.com"+"\n"+
										"DESCRIPTION:"+adatok[i].description+"\n"+
										"SUMMARY:"+adatok[i].name+"\n"+
										"LOCATION:"+adatok[i].location+"\n"+
										"CATEGORIES:"+adatok[i].categoryName+"\n"+
										"TRANSP:TRANSPARENT\n";
			if (reminder != ""){
				data = data + 			"BEGIN:VALARM\n"+
										"ACTION:DISPLAY\n"+
										"TRIGGER:-P"+reminder+
										"DESCRIPTION:This is an event reminder\n"+
										"END:VALARM\n";
			}
			data = data + "END:VEVENT\n";
        }
		
		data = data + "END:VCALENDAR"
		
		if (savetoFile(data) == 0){
			alert("Export succesful");
		}
		else{
			alert("Sorry. Export faild");
		}

}

/**	
	*@class importExport
	*@description Egy FilePicker segitségével kiválasztunk egy filet és a bene lévö informáciokat visszatériti egy stringbe.
	*
	*@author Propszt Istvan
	*
	*@return {string}
*/

function readFromFile(){
	
	const nsIFilePicker = Components.interfaces.nsIFilePicker;
    var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker); 
    fp.init(window, "Select a File", nsIFilePicker.modeOpen);
    fp.appendFilter("iCalendar","*.ics");

    var rv = fp.show();
    
    if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
        var file = fp.file;
        var data = "";
        var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].
              createInstance(Components.interfaces.nsIFileInputStream);
        var cstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].
              createInstance(Components.interfaces.nsIConverterInputStream);
        fstream.init(file, -1, 0, 0);
        cstream.init(fstream, "UTF-8", 0, 0);
        let (str = {}){
            let read = 0;
            do { 
                read = cstream.readString(0xffffffff, str); // read as much as we can and put it in str.value
                data += str.value;
            } while (read != 0);
        }
        cstream.close(); // this closes fstream
	
		return data;
	}
	
	return "";
}

/**
	*@class importExport
	*@description Import data from file and insert to datebase
	*
	*@author Propszt Istvan
	*
	*@see getCategoryIndex
	*@see newCategory
	*@see getRepeatIndex
	*@see getReminderIndex
	*@see newReminder
	*@see newEvent
	*@see readFromFile
*/

function importF(){

		var data = readFromFile();

        var Events = data.split("BEGIN:VEVENT");
        var tomb = new Array();

        for (var i = 1 ; i<Events.length ; i++){
            tomb.push(record());

            var j = Events[i].indexOf("SUMMARY:");
            tomb[i-1].summary = "";
//SUMMARY
            if (j > -1){
                j = j+8;
                while (Events[i][j] != "\n"){
                    tomb[i-1].summary = tomb[i-1].summary + (Events[i][j]);
                    j++;
                }
            }
//DESCRIPTION
            j = Events[i].indexOf("DESCRIPTION:");
            var k = Events[i].indexOf("BEGIN:VALARM");
            tomb[i-1].description = "";
            if ( k > -1 )
            if ( j > -1 && k > j ){
                j = j+12;
                while (Events[i][j] != "\n"){
                    tomb[i-1].description = tomb[i-1].description + (Events[i][j]);
                    j++;
                }
            }
            else{
               if ( j > -1 ){
                   j = j+12;
                   while (Events[i][j] != "\n"){
                       tomb[i-1].description = tomb[i-1].description + (Events[i][j]);
                       j++;
                }
               }
            }
//LOCATION
            j = Events[i].indexOf("LOCATION:");
            tomb[i-1].location = "";
            if (j > -1){
                j = j+9;
                while (Events[i][j] != "\n"){
                    tomb[i-1].location = tomb[i-1].location + (Events[i][j]);
                    j++;
                }
            }
//CATEGORIES
            j = Events[i].indexOf("CATEGORIES:");
            tomb[i-1].categories = "";
            if (j > -1){
                j = j+11;
                while (Events[i][j] != "\n"){
                    tomb[i-1].categories = tomb[i-1].categories + (Events[i][j]);
                    j++;
                }
				
            }
			if (tomb[i-1].categories == ""){
					tomb[i-1].categories = "Other";
			}
				
			if (getCategoryIndex(tomb[i-1].categories) == -1){
					 newCategory(tomb[i-1].categories);
			 }
			
//Start Date & Time
            j = Events[i].indexOf("DTSTART");
            if (j > -1){
                j = j+7;
                while (Events[i][j] != ":"){
                    j++;
                }
                j++;
         
                tomb[i-1].syear =new Number(Events[i][j]+Events[i][j+1]+Events[i][j+2]+Events[i][j+3]);
                j = j+4;
                tomb[i-1].smonth = new Number(Events[i][j]+Events[i][j+1]);
                j = j+2;
                tomb[i-1].sday = new Number(Events[i][j]+Events[i][j+1]);
                j = j+2;
                if (Events[i][j] == "T"){
                    j++;
                    tomb[i-1].shour = new Number(Events[i][j]+Events[i][j+1]);
                    j = j+2;
                    tomb[i-1].sminute = new Number(Events[i][j]+Events[i][j+1]);
                }
                else{
                    tomb[i-1].shour = 0;
                    tomb[i-1].sminute = 0;
                }
              
            }
//End Date & Time
            j = Events[i].indexOf("DTEND");
            if (j > -1){
                j = j+5;
                while (Events[i][j] != ":"){
                    j++;
                }
                j++;
                tomb[i-1].eyear = new Number(Events[i][j]+Events[i][j+1]+Events[i][j+2]+Events[i][j+3]);
                j = j+4;
                tomb[i-1].emonth = new Number(Events[i][j]+Events[i][j+1]);
                j = j+2;
                tomb[i-1].eday = new Number(Events[i][j]+Events[i][j+1]);
                j = j+2;
                if (Events[i][j] == "T"){
                    j++;
                    tomb[i-1].ehour = new Number(Events[i][j]+Events[i][j+1]);
                    j = j+2;
                    tomb[i-1].eminute = new Number(Events[i][j]+Events[i][j+1]);
                }
                else{
                    tomb[i-1].ehour = 0;
                    tomb[i-1].eminute = 0;
                }
              
            }
//Repeat
			j = Events[i].indexOf("RRULE:FREQ=");
			var name2 = "";
			if ( j > -1){
				j = j + 11;
				while ( Events[i][j] >= "A" && Events[i][j] <= "Z"){
					name2 = name2 + Events[i][j];
					j++;
				}
			}
			var name = name2.valueOf();
			switch (name)
			{
			          
			case "YEARLY":
			    tomb[i-1].repeatN = "Yearly";
				
				break;
			case "MONTHLY":
				tomb[i-1].repeatN = "Monthly";
				
				break;
			case "WEEKLY":
				tomb[i-1].repeatN = "Weekly";
				
				break;
				
			case "DAILY":
				tomb[i-1].repeatN = "Daily";
				
				break;
			default:
				tomb[i-1].repeatN = "No repeat";
					

			}
			

			if ( getRepeatIndex( tomb[i-1].repeatN ) == -1 ){
				tomb[i-1].repeatN = "No repeat";
			}
//Reminder

			j = Events[i].indexOf(":-P");
			j = j + 3;
			if ( j > -1 ){
				name = "";
				var szam = 0;
				var karakter = "";
				tomb[i-1].reminderN = "Befor "
			
				while (karakter != "\n"){
					name = "";
					while ( Events[i][j] >= "0" && Events[i][j] <= "9"){
						name = name + Events[i][j];
						j++;
					}
					
					karakter = Events[i][j];
					j++;
					switch(karakter)
					{
						case "W":
							szam = szam + parseInt(name)*7*60*24;
							tomb[i-1].reminderN = tomb[i-1].reminderN + name + " Week , ";
							break;
						case "D":
							szam = szam + parseInt(name)*60*24;
							tomb[i-1].reminderN = tomb[i-1].reminderN + name + " Day , ";
							break;
						case "H":
							szam = szam + parseInt(name)*60;
							tomb[i-1].reminderN = tomb[i-1].reminderN + name + " Hour , ";
							break;
						case "M":
							szam = szam + parseInt(name);
							tomb[i-1].reminderN = tomb[i-1].reminderN + name + " minute";
							break;
					}
				}
			
				if (tomb[i-1].reminderN.charAt(tomb[i-1].reminderN.length - 2) == ","){
					tomb[i-1].reminderN = tomb[i-1].reminderN.substr(0,tomb[i-1].reminderN.length - 3)
				}
			}
			else{
				tomb[i-1].reminderN = "No Reminder";
				szam = 0 ;
			}
			
			tomb[i-1].reminder = szam;
			if ( getReminderIndex( tomb[i-1].reminderN ) == -1 ){
				newReminder(tomb[i-1].reminder,tomb[i-1].reminderN);
			}

        }
		
		var db = 0;
//Insert to datebase	
        for (var i = 0 ; i<tomb.length ; i++){
			if ( newEvent(tomb[i].categories , tomb[i].reminderN, tomb[i].repeatN, tomb[i].shour, tomb[i].sminute, tomb[i].summary, tomb[i].location, tomb[i].description, tomb[i].syear,
			tomb[i].smonth,  tomb[i].sday,  tomb[i].eyear, tomb[i].emonth, tomb[i].eday, tomb[i].ehour,  tomb[i].eminute) == 0 ){
				db++;
			}
        }
		
		alert(tomb.length+" eseményt volt a fileba\n"+db+" eseményt sikerült feldolgozni");
}

/**
	*@class importExport
	*@description Create and return a record.
	*
	*@author Propszt Istvan
	*
	*@return {record} 
*/

function record(){
    return {summary:"Nev",    //summary = Event name
            description:"leírás",
            location:"hely",
            categories:"kategoria",
            reminderN:"",
			reminder:0,
            repeatN:"",
			repeat:0,
            shour:12,         //s = Start
            sminute:01,
            syear:1990,
            smonth:1,
            sday:1,
            ehour:12,         //e = End
            eminute:01,
            eyear:1990,
            emonth:1,
            eday:1}
}

/**
	*@class importExport
	*@description If the namber is less than 10 insert a 0 befor number and convert to string.
	*
	*@author Propszt Istvan
	*
	*@param {number}
	*@return {string}  
*/

function doublenumber(nr){
	if (nr<10){
		return("0"+nr);
	}
	return(""+nr);
}

var vcalendar = "BEGIN:VCALENDAR\nPRODID:-//Mozilla.org/NONSGML Mozilla Calendar V1.1//EN\nVERSION:2.0\n";
var vtimezone = "BEGIN:VTIMEZONE\nTZID:Europe/Bucharest\nX-LIC-LOCATION:Europe/Bucharest\nBEGIN:DAYLIGHT\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0300\nTZNAME:EEST\nDTSTART:19700329T030000\nRRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\nEND:DAYLIGHT\nBEGIN:STANDARD\nTZOFFSETFROM:+0300\nTZOFFSETTO:+0200\nTZNAME:EET\nDTSTART:19701025T040000\nRRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\nEND:STANDARD\nEND:VTIMEZONE\n";